package com.itCar.base.api.wxApi.wxAuth.controller;

import com.itCar.base.api.wxApi.wxAuth.util.WxAuthUtil;
import com.itCar.base.config.result.ResultBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName: WeChatController
 * @Description: TODO
 * @author: liuzg
 * @Date: 2022/8/31 14:46
 * @Week: 星期三
 * @Version: v1.0
 */
@Slf4j
@RestController
@RequestMapping(value = "/admin")
@Api(tags = "微信：验证服务器有效性")
public class WeChatController {

    // 微信发送的token和此处要求一致
    private static final String TOKEN = "amnesiaclover0218";

    @ApiOperation(value = "验证")
    @GetMapping(value = "auth")
    public ResultBody wxAuth(HttpServletRequest request, HttpServletResponse response) {
        // 取出微信传入的参数
        String signature = request.getParameter("signature");
        String echostr = request.getParameter("echostr");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        System.out.println("signature: " + signature + ",echostr: " + echostr + ",timestamp: " + timestamp + ",nonce: " + nonce);
        // 校验证请求
        if (WxAuthUtil.check(timestamp, nonce, TOKEN, signature)) {
            try {
                response.reset();
                ServletOutputStream out = response.getOutputStream();
                // 原样返回echostr参数
                out.print(echostr);
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            System.out.println("接入成功");
        } else {
            System.out.println("接入失败");
        }
        return ResultBody.success("验证成功");
    }

    @ApiOperation(value = "接收消息和事件推送")
    @PostMapping(value = "receive")
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 处理消息和事件推送
        Map<String, String> requestMap = WxAuthUtil.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        // 准备回复的数据包 （如果不行就换成一行 去掉所有空格） 测试使用，真实场景 使用另一种
//        String respXml = "<xml> " +
//                            "<ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName> " +
//                            "<FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName> " +
//                            "<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>" +
//                            " <MsgType><![CDATA[text]]></MsgType> " +
//                            "<Content><![CDATA[hello, wechat!]]></Content> " +
//                        "</xml>";
        String respXml = WxAuthUtil.getResponse(requestMap);
        ServletOutputStream out = response.getOutputStream();
        out.print(respXml);
        out.flush();
        out.close();

    }




    // 解析xml
    public void parseXML(HttpServletRequest request) throws IOException {
        ServletInputStream is = request.getInputStream();
        byte[] b = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = is.read(b)) != -1) {
            sb.append(new String(b, 0, len));
        }
        System.out.println(sb.toString());
    }


}
